//
//  JSONAdapter.swift
//  Link
//
//  Created by melvyn on 2018/9/21.
//  Copyright © 2018 NEET. All rights reserved.
//

import Foundation

protocol JSONAdapterType {
    static func model<T: Decodable>(of aClass: T.Type, from: Data) throws -> T
    static func models<T: Decodable>(of aClass: T.Type, from: Data) throws -> [T]
    static func encode<T: Encodable>(_ value: T) throws -> Data
    static func jsonObject<T: Encodable>(from value: T) throws -> Any
}
extension JSONAdapterType {
    static func model<T>(of aClass: T.Type, from: Data) throws -> T where T: Decodable {
        return try JSONDecoder.init().decode(aClass, from: from)
    }
    
    static func models<T>(of aClass: T.Type, from: Data) throws -> [T] where T: Decodable {
        return try JSONDecoder.init().decode([T].self, from: from)
    }
    
    static func encode<T>(_ value: T) throws -> Data where T: Encodable {
        return try JSONEncoder().encode(value)
    }
    
    static func jsonObject<T>(from value: T) throws -> Any where T: Encodable {
        return try JSONSerialization.jsonObject(with: try JSONEncoder().encode(value), options: .allowFragments)
    }
}

class JSONAdapter: JSONAdapterType {}
